#include  "head.h"
int recvn(int sockfd, void *buf, int length){
    int total = 0;
    char *p = (char *)buf;
    while(total < length){
        ssize_t sret = recv(sockfd,p+total,length-total,0);
        total += sret;
    }
    return total;
}
int recvFile(int sockfd, char *buf){
    train_t train;
    char filename[4096] = {0};
    strcpy(filename,buf);
    /* recv(sockfd,&train.length,sizeof(train.length),MSG_WAITALL); */
    /* recv(sockfd,train.data,train.length,MSG_WAITALL); */
    /* memcpy(filename,train.data,train.length); */

    int fd = open(filename,O_RDWR|O_CREAT|O_TRUNC,0666);
    ERROR_CHECK(fd,-1,"open");
    //
    off_t filesize;
    recvn(sockfd,&train.length,sizeof(train.length));
    recvn(sockfd,train.data,train.length);
    memcpy(&filesize,train.data,train.length);
    /* printf("filesize = %ld\n",filesize); */
    off_t cursize = 0;
    off_t lastsize = 0;
    off_t slice = filesize/10000;
    //
    /* recv(netfd,&train.length,sizeof(train.data),0);// */
    while(1){
        recvn(sockfd,&train.length,sizeof(train.length));
        if(train.length == 0)
            break;
        cursize += train.length;
        if(cursize - lastsize > slice){
            printf("%5.2lf%%\r",100.0*cursize/filesize);
            fflush(stdout);
            lastsize = cursize;
        }
        recvn(sockfd,train.data,train.length);
        write(fd,train.data,train.length);
    }
    printf("100.00%%\n");
    close(fd);
    return 0;
}

